package com.ruoyi.project.system.controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.vo.UserProductPriceVo;
import com.ruoyi.project.system.mapper.SmIdentityMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysRoleService;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.CacheConstants.UPGRADE_COST;
import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD;
import static com.ruoyi.common.utils.DateUtils.parseDateToStr;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SmIdentityMapper smIdentityMapper;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/statistic")
    public AjaxResult statistic() {
        AjaxResult result = new AjaxResult();
        Map<String, Long> map = userMapper.statisticUser();
        result.putAll(map);
        result.put("TN", map.get("R2") + map.get("R3") + map.get("R4") + map.get("R5") + map.get("R6"));
        result.putAll(userMapper.statisticQueryAndPayAndIncome());
        return result;
    }

    /**
     * 获取用户升级信息
     */
    @GetMapping("/upgrade")
    public AjaxResult upgrade() {
        Map<String, String> roleInfo = userMapper.selectRoleInfoByUserId(SecurityUtils.getUserId());
        String roleKey = roleInfo.get("roleKey");
        AjaxResult result = new AjaxResult();
        result.put("roleName", roleInfo.get("roleName"));
        if ("ordinary".equals(roleKey)) {
            result.put("member", redisCache.getCacheObject(UPGRADE_COST + "ordinary->member"));
            result.put("captain", redisCache.getCacheObject(UPGRADE_COST + "ordinary->captain"));
            result.put("region", redisCache.getCacheObject(UPGRADE_COST + "ordinary->region"));

            String areaCode = SecurityUtils.getLoginUser().getUser().getAreaCode();
            Date effectiveTime = smIdentityMapper.effectiveTimeByTypeAndAreaCode(areaCode, "region");
            result.put("regionEffectiveTime", effectiveTime != null ? parseDateToStr(YYYY_MM_DD, effectiveTime) : effectiveTime);

        } else if ("member".equals(roleKey)) {
            result.put("captain", redisCache.getCacheObject(UPGRADE_COST + "member->captain"));
            result.put("region", redisCache.getCacheObject(UPGRADE_COST + "member->region"));

            Integer parentId = SecurityUtils.getLoginUser().getUser().getParentId();
            if (parentId != null) {
                Long parentId_ = userMapper.queryParentId(parentId.longValue());
                if (parentId_ != null) {
                    result.put("regionEffectiveTime", parseDateToStr(YYYY_MM_DD, smIdentityMapper.effectiveTime(parentId_.longValue(), "region")));
                } else {
                    result.put("regionEffectiveTime", null);
                }
            } else {
                result.put("regionEffectiveTime", null);
            }
        } else if ("captain".equals(roleKey)) {
            result.put("region", redisCache.getCacheObject(UPGRADE_COST + "captain->region"));

            Integer parentId = SecurityUtils.getLoginUser().getUser().getParentId();
            if (parentId != null) {
                result.put("regionEffectiveTime", parseDateToStr(YYYY_MM_DD, smIdentityMapper.effectiveTime(parentId.longValue(), "region")));
            } else {
                result.put("regionEffectiveTime", null);
            }
        }
        Date date = smIdentityMapper.effectiveTime(SecurityUtils.getUserId(), roleKey);
        result.put("time", date != null ? parseDateToStr(YYYY_MM_DD, date) : null);
        return result;
    }

    @GetMapping("/teamMember")
    public AjaxResult teamMember() {
        Long userId = SecurityUtils.getUserId();
        return success(userMapper.queryMember(userId));
    }

    @GetMapping("/getIC")
    public AjaxResult getInviteCode(@NotBlank String info) {
        Long userId = SecurityUtils.getUserId();
        String inviteCode = userMapper.getInviteCode(userId, "REG", info);
        if (StringUtils.isEmpty(inviteCode)) {
            inviteCode = IdUtils.fastSimpleUUID().substring(0, 6);
            userMapper.insertInviteCode(userId, "REG", info, inviteCode);
        }
        return success(inviteCode);
    }

    @GetMapping("/updateIC")
    public AjaxResult updateInviteCode(@NotBlank String olc) {
        String newInviteCode = IdUtils.fastSimpleUUID().substring(0, 6);
        userMapper.updateInviteCode(newInviteCode, olc);
        return success(newInviteCode);
    }

    @Anonymous
    @GetMapping("/invite")
    public AjaxResult inviteCode(String type, String ic) {
        String code = userMapper.queryRegisterAreaCode(type, ic);
        if (StringUtils.isEmpty(code)) {
            return error();
        }
        return success(code);
    }

    @GetMapping("/payMentAccount")
    public AjaxResult payMentAccount() {
        Map<String, String> map = userMapper.selectAliAccount(SecurityUtils.getUserId());
        if (map == null) {
            return warn("未填写提现账户信息");
        } else {
            return success(map);
        }
    }

    /**
     * 验证修改收款账户
     */
    @PutMapping("/setPayMentAccount")
    public AjaxResult setPayMentAccount(@RequestBody Map<String, String> params) {
        if (StringUtils.isEmpty(params.get("code"))) {
            return AjaxResult.error("验证码为空");
        } else if (StringUtils.isEmpty(params.get("alipayName"))) {
            return AjaxResult.error("支付宝姓名为空");
        } else if (StringUtils.isEmpty(params.get("alipayAccount"))) {
            return AjaxResult.error("支付宝账号为空");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + SecurityUtils.getUsername();
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (!params.get("code").equals(captcha)) {
            return AjaxResult.error("验证码错误");
        }
        return success(userService.updateUser(new SysUser(SecurityUtils.getUserId(), params.get("alipayName"), params.get("alipayAccount"))));
    }

    @GetMapping("/teamStatistics")
    public AjaxResult teamStatistics() {
        AjaxResult result = new AjaxResult();
        Long userId = SecurityUtils.getUserId();
        result.put("people", userMapper.teamNumberOfPeople(userId));
        result.put("query", userMapper.teamNumberOfQuery(userId));
        result.put("income", userMapper.teamNumberOfIncome(userId));
        return result;
    }

    /**
     * 获取用户身份信息
     */
    @GetMapping("/member")
    public AjaxResult member() {
        AjaxResult result = new AjaxResult();
        Long userId = SecurityUtils.getUserId();
        Integer roleId = SecurityUtils.getLoginUser().getUser().getRoleId();
        result.put("roleName", roleService.selectRoleById(roleId.longValue()).getRoleName());
        result.put("registerArea", userMapper.queryRegisterAreaName(userId));

        String info = "";
        Date time = null;
        if (roleId == 2) {
            info = "管理区域：";
            List<String> list = userMapper.queryRegionCaptainAreaName(userId);
            for (String s : list) {
                info += (s + " ");
            }
            info += ("| 队长：" + userMapper.queryCaptainCount(userId) + "名 | ");
            info += ("队员：" + userMapper.queryMemberCount(userId) + "名");
            time = smIdentityMapper.effectiveTime(userId, "region");
        }
        if (roleId == 3) {
            info += ("队员：" + userMapper.queryMemberCount(userId) + "名");
            time = smIdentityMapper.effectiveTime(userId, "captain");
        }
        result.put("info", info);
        result.put("time", time != null ? parseDateToStr(YYYY_MM_DD, time) : null);
        return result;
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/productPriceList")
    public TableDataInfo productPriceList(@NotBlank SysUser user) {
        startPage();
        List<SysUser> users = userMapper.selectUserList_(user);
        List<UserProductPriceVo> userProductPriceVos = userService.selectUserProductVoList(users);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(userProductPriceVos);
        rspData.setTotal(new PageInfo(users).getTotal());
        return rspData;
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
//        List<SysRole> roles = roleService.selectRoleAll();
//        ajax.put("roles", SecurityUtils.getLoginUser().getUser().isAdmin() ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);

//            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        roleService.checkRoleDataScope(user.getRoleId());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        roleService.checkRoleDataScope(user.getRoleId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

}

